package com.ljx.service;

import com.ljx.dao.StockDao;
import com.ljx.entity.Stock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2022/12/8 15:12
 * @Version 1.0
 */
@Service
public class StockServiceImpl_redisson {
	@Resource
	private StockDao stockDao;

	@Autowired
	private RedissonClient redissonClient;

		public  String decrement(Integer productid) {
			// 获取锁对象，
			RLock lock = redissonClient.getLock("product::" + productid);
			// 设置为30秒(必须为30秒)
			lock.lock(30,TimeUnit.SECONDS);
				try{
				// 1.查找指定商品的库存
				Stock stock = stockDao.selectById(productid);
				// 2.判断库存数是否大于0
				if (stock.getStock() > 0) {
					// 3.减库存(实体类减去库存数据库也要减去)
					stock.setStock(stock.getStock() - 1);
					stockDao.updateById(stock);
					System.out.println("商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个");
					return "商品编号为:" + productid + "的商品库存剩余:" + stock.getStock() + "个";
				} else {
					System.out.println("商品编号为:" + productid + "的商品库存不足。");
					return "商品编号为:" + productid + "的商品库存不足。";
				}

				}finally {
					// 释放锁资源
					lock.unlock();
				}



		}

}
